package com.jiutong.meipengdai.ui.activitys;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.base.BaseActivity;
import com.jiutong.meipengdai.common.Constants;
import com.jiutong.meipengdai.entity.AccountSettingRespond;
import com.jiutong.meipengdai.entity.PicUploadRespond;
import com.jiutong.meipengdai.http.model.interfaces.CheckLoginInterface;
import com.jiutong.meipengdai.http.model.interfaces.MyUserInfoBiz;
import com.jiutong.meipengdai.http.model.requests.ImageUploadRequest;
import com.jiutong.meipengdai.http.model.requests.MyAccountRequest;
import com.jiutong.meipengdai.http.present.MyUserInfoPresent;
import com.jiutong.meipengdai.http.subscribers.ProgressSubscriber;
import com.jiutong.meipengdai.http.subscribers.SubscriberOnNextListener;
import com.jiutong.meipengdai.utils.ImageUtil;
import com.jiutong.meipengdai.utils.PermissionUtil;
import com.jiutong.meipengdai.utils.SpConfig;
import com.jiutong.meipengdai.views.GlideCircleTransform;
import com.jiutong.meipengdai.views.dialog.BaseDialog;
import com.jiutong.meipengdai.views.dialog.SexDialog;
import com.jiutong.meipengdai.views.dialog.TimePickerDialog;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 個人中心
 * Created by suxi on 2017/5/31.
 */

@CheckLoginInterface
public class UserInfoAcitivity extends BaseActivity implements MyUserInfoBiz {

    private final int REQUEST_ALBUM = 0;
    private final String IMAGE_TYPE = "image/*";
    private final int REQUEST_CAMERA = 1;
    private final int REQUEST_REALNAME = 2;

    @Bind(R.id.rl_back)
    RelativeLayout rl_back;
    @Bind(R.id.iv_user_icon)
    ImageView iv_user_icon;
    @Bind(R.id.rl_birthday)
    RelativeLayout rlBirthday;
    @Bind(R.id.tv_my_birthday)
    TextView tv_my_birthday;
    @Bind(R.id.rl_address)
    RelativeLayout rlAddress;
    @Bind(R.id.rl_real_name)
    RelativeLayout rl_real_name;
    @Bind(R.id.tv_my_real_name)
    TextView tv_my_real_name;
    @Bind(R.id.rl_my_sex)
    RelativeLayout rl_my_sex;
    @Bind(R.id.tv_my_sex)
    TextView tv_my_sex;
    @Bind(R.id.rl_head)
    RelativeLayout rl_head;
    @Bind(R.id.iv_arrow)
    ImageView iv_arrow;
    @Bind(R.id.rl_membershipCard)
    RelativeLayout rl_membershipCard;
    @Bind(R.id.tv_my_black_card)
    TextView tv_my_black_card;
    @Bind(R.id.tv_user_address)
    TextView tv_user_address;

    private String sex;
    private String realName;
    private String headerImg;
    private String birthday;
    private String membershipCard;
    private String imgPath;
    private String cardNumber;
    private String vip_num;
    private Bitmap bitmap, bm;

    private BaseDialog dialog;
    private TimePickerDialog timePickerDialog;
    private SexDialog sexDialog;
    private BaseDialog authDialog;

    private MyUserInfoPresent myUserInfoPresent;
    private MyAccountRequest mRequest;
    private SubscriberOnNextListener onNextListener;
    private HashMap<String, Object> fieldsMap;
    private ProgressSubscriber progressSubscriber;

    /**
     * 判断sdcard是否被挂载
     */
    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void initDate(Bundle savedInstanceState) {
        if (savedInstanceState != null)
            imgPath = savedInstanceState.getString("picpath");
    }

    @Override
    protected void initView() {
        super.initView();
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText("个人信息");
        ButterKnife.bind(this);
        myUserInfoPresent = new MyUserInfoPresent(this, this);

        if (SpConfig.getInstance().getBool(Constants.ISAUTH_BOOLEAN)) {
            tv_my_real_name.setCompoundDrawables(null, null, null, null);
        }
    }

    private void initUserInfo() {
        if (mRequest == null) {
            mRequest = new MyAccountRequest();
        }
        onNextListener = new SubscriberOnNextListener<AccountSettingRespond>() {
            @Override
            public void onNext(AccountSettingRespond subjects) {
                AccountSettingRespond respond = (AccountSettingRespond) subjects;
                headerImg = respond.getData().getHeaderImg();

                SpConfig.getInstance().putString(Constants.HEADERIMG_STRING, headerImg);
                membershipCard = respond.getData().getMembershipCard();
                realName = respond.getData().getRealName();
                sex = respond.getData().getSex();
                birthday = respond.getData().getBirthDay();
                if (respond.getData().getAddresss().size() > 0) {
                    tv_user_address.setText("");
                }
                Glide.with(mContext).load("http://"+headerImg).transform(new CenterCrop(mContext), new GlideCircleTransform(mContext))
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .crossFade().into(iv_user_icon);
                if (!TextUtils.isEmpty(realName)) {
                    tv_my_real_name.setText(realName);
                }
                if (!TextUtils.isEmpty(membershipCard)) {
                    StringBuffer sb = new StringBuffer();
                    String str = membershipCard.substring(0, 4) + sb.append(" ") + membershipCard.substring(4, 8) + sb.append("") + membershipCard.substring(8, 12);
                    tv_my_black_card.setText(str);
                }
                if (sex != null) {
                    if (sex.equals("1")) {
                        tv_my_sex.setText("男");
                    } else if (sex.equals("2")) {
                        tv_my_sex.setText("女");
                    }
                }
                if (!TextUtils.isEmpty(birthday)) {
                    tv_my_birthday.setText(birthday);
                }

            }

            @Override
            public void onError(Throwable e) {

            }
        };
        fieldsMap = new HashMap<>();
        progressSubscriber = new ProgressSubscriber(onNextListener, mContext);
        mRequest.getAccountSetting(progressSubscriber, fieldsMap);

    }

    @OnClick({R.id.rl_birthday, R.id.rl_address, R.id.rl_back, R.id.rl_head, R.id.rl_membershipCard, R.id.rl_real_name, R.id.rl_my_sex})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_head:     //头像
                if (dialog == null) {
                    dialog = new BaseDialog.Builder().
                            layResuorce(R.layout.activity_user_info_head_dialog).
                            okViewClickEvent(R.id.tv_dialog_take_photo).
                            ok2ViewClickEvent(R.id.tv_dialog_phone).
                            cancelViewClickEvent(R.id.tv_dialog_cancel).
                            gravityStyle(Gravity.BOTTOM).
                            animResource(R.style.dialog_animation).
                            dialogWidth(-1).
                            build();
                    dialog.setOnDialogClickListener(new BaseDialog.OnDialogClickListener() {
                        @Override
                        public void onOkClick() {
                            //拍照
                            openCamera();
                            dialog.dismiss();
                        }

                        @Override
                        public void onOk2Click() {
                            //从手机相册
                            openAlbum();
                            dialog.dismiss();
                        }

                    });
                }
                dialog.show(getSupportFragmentManager(), TAG);

                break;
            case R.id.rl_membershipCard:  //黑金卡
                //没有实名认证
                if (TextUtils.isEmpty(realName)) {
                    showAutoDialog();
                    return;
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("membershipcard", membershipCard);
                    openActivity(MembershipCardActivity.class, bundle);
                }
                break;
            case R.id.rl_real_name: //真实姓名
                if (!SpConfig.getInstance().getBool(Constants.ISAUTH_BOOLEAN)) {
                    startActivityForResult(new Intent(this, RealNameActivity.class), REQUEST_REALNAME);
                }

                break;
            case R.id.rl_my_sex: //性别
                showSexDialog();
                break;
            case R.id.rl_birthday:  //出生日期
                timePickerDialog = new TimePickerDialog();
                timePickerDialog.setOnDialogClickListener(new TimePickerDialog.OnDialogClickListener() {
                    @Override
                    public void onBtnClick(String year, String month, String data) {
                        if (Integer.parseInt(month) < 10) {
                            month = "0" + month;
                        }
                        if (Integer.parseInt(data) < 10) {
                            data = "0" + data;
                        }
                        tv_my_birthday.setText(year + "-" + month + "-" + data);
                        myUserInfoPresent.editSexBirthday();
                        timePickerDialog.dismiss();
                    }
                });
                timePickerDialog.show(getSupportFragmentManager(), TAG);
                break;
            case R.id.rl_address:  //收货地址
                openActivity(AddressActivity.class);
                break;
            case R.id.rl_back:   //返回
                finish();
                break;
        }
    }

    private void showAutoDialog() {
        if (authDialog == null) {

            authDialog = new BaseDialog.Builder()
                    .layResuorce(R.layout.dialog_to_auto)
                    .animResource(R.style.dialog_animation_fade)
                    .okViewClickEvent(R.id.tv_goauth)
                    .outSideCancel(true)
                    .gravityStyle(Gravity.CENTER)
                    .build();

            authDialog.setOnDialogClickListener(new BaseDialog.OnDialogClickListener() {
                @Override
                public void onOkClick() {
                    Intent intent = new Intent();
                    intent.setClass(mContext, RealNameActivity.class);
                    startActivityForResult(intent, REQUEST_REALNAME);
                    authDialog.dismiss();
                }

                @Override
                public void onOk2Click() {

                }
            });
        }

        authDialog.show(getSupportFragmentManager(), TAG);
    }

    //显示性别dialog
    private void showSexDialog() {

        if (sexDialog == null) {
            sexDialog = new SexDialog();
            sexDialog.setOnDialogClickListener(new SexDialog.OnDialogClickListener() {
                @Override
                public void onBtnClick(String diraction) {
                    tv_my_sex.setText(diraction);
                    tv_my_sex.setTextColor(getResources().getColor(R.color.loan_desc));
                    myUserInfoPresent.editSexBirthday();
                }
            });
        }

        sexDialog.show(getSupportFragmentManager(), TAG);
    }

    private void openCamera() {

        //检查系统是否开启了拍照位置权限;检查系统是否开启了读写权限;
        if (!PermissionUtil.checkSelfPermission(this, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            return;
        }

        if (hasSdcard()) {
            Date date = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 格式化时间
            String filename = format.format(date) + ".jpg";
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 启动系统相机

            File fileFolder = new File(Environment.getExternalStorageDirectory()
                    + "/jiutong/");
            if (!fileFolder.exists()) { // 如果目录不存在，则创建一个名为"jiutong"的目录
                fileFolder.mkdir();
            }

            File jpgFile = new File(fileFolder, filename);
            imgPath = jpgFile.getPath();
            int currentapiVersion = android.os.Build.VERSION.SDK_INT;
            if (currentapiVersion < 24) {
                // 从文件中创建uri
                Uri uri = Uri.fromFile(jpgFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            } else {
                //兼容android7.0 使用共享文件的形式
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, jpgFile.getAbsolutePath());
                Uri uri = this.getApplication().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            }
//            Uri photoUri = Uri.fromFile(jpgFile); // 传递路径
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);// 更改系统默认存储路径

            startActivityForResult(intent, REQUEST_CAMERA);
        }
    }

    private void openAlbum() {

        boolean isKitKatO = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        Intent getAlbum;
        if (isKitKatO) {
            getAlbum = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        } else {
            getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
        }
        getAlbum.setType(IMAGE_TYPE);

        startActivityForResult(getAlbum, REQUEST_ALBUM);
    }

    /**
     * 处理图片路径，并显示出来
     */
    private void handleheaderImgToShow() {
        Glide.with(mContext).load(new File(imgPath)).transform(new CenterCrop(mContext), new GlideCircleTransform(mContext))
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .crossFade().into(iv_user_icon);
        bitmap = BitmapFactory.decodeFile(imgPath);
        if (bitmap != null) {
            imageUpload();
        }
    }

    //接收照片
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) { // 如果返回数据
            if (requestCode == REQUEST_CAMERA) { // 拍照数据
                handleheaderImgToShow();
            } else if (requestCode == REQUEST_ALBUM) {//相册
                // 从相册返回的数据
                if (data != null) {
                    Uri uri = data.getData();
                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    if (bitmap != null) {
                        imageUpload();
                    }
                }
            } else if (data != null && requestCode == REQUEST_REALNAME) {  //返回真实姓名
                tv_my_real_name.setText(data.getExtras().getString("realName"));
                vip_num = data.getExtras().getString("cardNumber");  //实名认证传过来的会员卡号
                if (!TextUtils.isEmpty(vip_num)) {
                    tv_my_black_card.setText(vip_num);               //如果传了，就显示传过来的
                } else {
                    tv_my_black_card.setText(membershipCard);        //没有传，就显示系统分配的
                }
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("picpath", imgPath);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            imgPath = savedInstanceState.getString("picpath");
        }
        super.onRestoreInstanceState(savedInstanceState);
    }


    private void imageUpload() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                //压缩bitmap
                Matrix matrix = new Matrix();
                matrix.setScale(0.125f, 0.125f);
                bm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                        bitmap.getHeight(), matrix, true);
                final String strByBase64 = ImageUtil.Bitmap2StrByBase64(bm);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        SubscriberOnNextListener<PicUploadRespond> nextListener = new SubscriberOnNextListener<PicUploadRespond>() {

                            @Override
                            public void onNext(PicUploadRespond object) {
                                PicUploadRespond respond = (PicUploadRespond) object;
                                if (respond.getResCode().equals("200")) {
                                    toastShortShow("图片上传成功");
//                                    headerImg = respond.getFileAddress();
                                    initUserInfo();
                                } else {
                                    toastShortShow(respond.getResDesc());
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
//                toastShortShow("图片上传失败");
                            }
                        };

                        HashMap<String, Object> fileMap = new HashMap<>();
                        fileMap.put("fileType", "jpg");
                        fileMap.put("uploadType", "1");
                        fileMap.put("fileContent", strByBase64);
                        fileMap.put("operatorId", "");
                        ImageUploadRequest uploadService = new ImageUploadRequest();
                        uploadService.imgUpload(new ProgressSubscriber(nextListener, mContext), fileMap);
                    }
                });
            }
        }).start();
    }

    @Override
    public short getSex() {
        if (tv_my_sex.getText().toString().equals("男")) {
            return 1;
        } else if (tv_my_sex.getText().toString().equals("女")) {
            return 2;
        } else
            return 0;
    }

    @Override
    public String getBirthday() {
        return tv_my_birthday.getText().toString();
    }

    @Override
    public void onSuccess(Object object) {
        AccountSettingRespond respond = (AccountSettingRespond) object;
        if (respond.getResCode().equals("200")) {
            toastShortShow(respond.getResDesc());
        } else {
            toastShortShow(respond.getResDesc());
        }
    }

    @Override
    public void onError(Throwable e) {
    }

    @Override
    protected void onResume() {
        super.onResume();
        initUserInfo();
    }
}
